package com.cheer.ba.view.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.CalculateMoneyModel;
import com.cheer.ba.model.CommonModel;
import com.cheer.ba.model.ConstantModel;
import com.cheer.ba.model.MyAddressModel;
import com.cheer.ba.model.OilDetailBannerModel;
import com.cheer.ba.model.OilDetailsModel;
import com.cheer.ba.model.OilSendModel;
import com.cheer.ba.presenter.impl.MyAddressPresenter;
import com.cheer.ba.presenter.impl.TransitPresenter;
import com.cheer.ba.utils.Currency;
import com.cheer.ba.utils.ImageUtils;
import com.cheer.ba.utils.Protect;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.pickerview.Util;
import com.cheer.wheelview.DateSelectionDialog;
import com.cheer.wheelview.TimeSelectionDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 描述 ：柴油批发下单界面
 * 作者 ：hq
 * 时间 ：2017/7/1 18:30
 */
public class OilPullOrderAty extends BaseCommAty {

    //没有地址
    @BindView(R.id.id_add_address_linear)
    LinearLayout mLinearNoAddress;

    //有地址
    @BindView(R.id.id_choose_address_rela)
    RelativeLayout mRelaHadAddress;
    //收货人
    @BindView(R.id.id_goods_name_txt)
    TextView mTxtGoodsName;
    private String mSaveGoodsName;
    //收货电话
    @BindView(R.id.id_goods_tel_txt)
    TextView mTxtGoodsTel;
    private String mSaveGoodsTel;
    //收货地址
    @BindView(R.id.id_goods_address_txt)
    TextView mTxtGoodsAddress;
    private String mSaveGoodsAddress = "";

    //商品图片
    @BindView(R.id.id_oil_pic_img)
    ImageView mImgoilPic;
    //商品价格
    @BindView(R.id.id_oil_price_txt)
    TextView mTxtOilPrice;
    //商品标题
    @BindView(R.id.id_oil_title_txt)
    TextView mTxtOilTitle;
    //商品密度
    @BindView(R.id.id_oil_density_txt)
    TextView mTxtOilDensity;
    //中国石油
    @BindView(R.id.id_oil_type_txt)
    TextView mTxtOilType;

    //减
    @BindView(R.id.id_order_desc_txt)
    TextView mTxtDesc;
    //  加
    @BindView(R.id.id_order_add_txt)
    TextView mTxtAdd;
    //   输入框
    @BindView(R.id.id_order_num_edit)
    EditText mEditOil;
    private String mSaveBuyOil;
    //   配送方式
    @BindView(R.id.id_send_way_txt)
    TextView mTxtSendWay;
    //1  自提 2 配送
    private String mSaveSendWay = "";
    //配送方式
    private ArrayList<CommonModel> mSends = new ArrayList<CommonModel>();
    //   发票
    @BindView(R.id.id_invoice_txt)
    TextView mTxtInvoice;
    //发票方式
    private ArrayList<CommonModel> mInvoices = new ArrayList<CommonModel>();
    //   期望送达时间
    @BindView(R.id.id_wish_time_txt)
    TextView mTxtWishTime;
    private String mSaveWishTime;
    // 时间选择器
    private DateSelectionDialog mDateDialog;
    //   备注
    @BindView(R.id.id_remark_edit)
    EditText mEditRemark;
    private String mSaveRemark;
    //   总金额
    @BindView(R.id.id_total_price_txt)
    TextView mTxtTotalPrice;
    private String mSaveTotalPrice;
    //   定金
    @BindView(R.id.id_pay_price_txt)
    TextView mTxtPayPrice;
    private String mSavePay;

    //记录详情数据
    private OilDetailsModel mOilDetailsModel;
    //记录定金计算
    private CalculateMoneyModel mCalculateModel;
    //记录自提最少多少吨起 单位吨
    private double mRecordUserGet;
    //记录配送需要多少吨起
    private double mRecordSend;

    private TransitPresenter mTransitPresenter;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_pull_oil_order, null, false));
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initPresenter() {
        presenter = new MyAddressPresenter();

        mTransitPresenter = new TransitPresenter();
        mTransitPresenter.attachView(this);
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);

        setTitleText("去支付");
        mOilDetailsModel = (OilDetailsModel) getIntent().getSerializableExtra(IntentKey.General.KEY_MODEL);
        mCalculateModel = (CalculateMoneyModel) getIntent().getSerializableExtra(IntentKey.General.KEY_DATA);
        mRecordUserGet = getIntent().getDoubleExtra(IntentKey.FindOil.ZITI_OIL_NUM, 0);
        mRecordSend = getIntent().getDoubleExtra(IntentKey.FindOil.SEND_OIL_NUM, 0);

        if (null == mOilDetailsModel || null == mCalculateModel) {
            dataStatus(2);
            return;
        }
        mDateDialog = new DateSelectionDialog(aty);
        mDateDialog.setOnChooseDateListener(new DateSelectionDialog.ChooseDateListener() {
            @Override
            public void chooseDate(String selectData, boolean flag) {
                //选择的日期
                mTxtWishTime.setText(selectData);
                mSaveWishTime = StringUtils.dateToStamp(selectData, "yyyy-MM-dd");
            }
        });
        //获得我的默认地址
        ((MyAddressPresenter) presenter).getMyDefaultAddress(true);
    }

    @Override
    public void initData() {
        mEditOil.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSaveBuyOil = s + "";
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                int len = text.length();
                if (len == 1 && text.equals("0")) {
                    s.clear();
                } else {
//                    if (!StringUtils.isEmpty(mSaveSendWay)) {
//                        if (TextUtils.equals("1", mSaveSendWay)) {
//                            //自提
//                            if (Integer.parseInt(text) < mRecordUserGet) {
//                                mEditOil.setText((int) mRecordUserGet + "");
//                            }
//                        } else {
//                            // 配送
//                            if (Integer.parseInt(text) < mRecordSend) {
//                                mEditOil.setText((int) mRecordSend + "");
//                            }
//                        }
//                    }
                }
            }
        });
    }

    /**
     * 选滚轮
     *
     * @param mStrs
     * @param flag  1 配送方式
     */
    public void chooseWheel(final ArrayList<String> mStrs, final int flag) {
        Util.alertBottomWheelOption(aty, mStrs, new Util.OnWheelViewClick() {
            @Override
            public void onClick(View view, int postion) {
                if (flag == 1) {
                    mSaveSendWay = mSends.get(postion).position;
                    mTxtSendWay.setText(mSends.get(postion).name);
                    if (TextUtils.equals("1", mSaveSendWay)) {
                        //自提
                        mTransitPresenter.getSystemConstant("since_min", ConstantTag.GET_SINCE_MIN);
                    } else {
                        //配送
                        mTransitPresenter.getSystemConstant("distribution_min", ConstantTag.GET_DISTRIBUTION_MIN);
                    }
                }
            }
        }, 0);
    }

    /**
     * 检测
     */
    public boolean checkData() {
        mSaveBuyOil = mEditOil.getText().toString().trim();
        mSaveRemark = mEditRemark.getText().toString().trim();
        if (mLinearNoAddress.getVisibility() == View.VISIBLE) {
            SVProgressHUD.showInfoWithStatus(aty, "请填写收货地址");
        } else {
            if (StringUtils.isEmpty(mSaveWishTime)) {
                SVProgressHUD.showInfoWithStatus(aty, "请选择期望到达时间");
            } else {
                if (StringUtils.isEmpty(mSaveSendWay)) {
                    SVProgressHUD.showInfoWithStatus(aty, "请选择配送方式");
                } else {
                    if (StringUtils.isEmpty(mSaveBuyOil)) {
                        SVProgressHUD.showInfoWithStatus(aty, "请填写需要购买的油量");
                    } else {
                        int mBuyOil = Integer.parseInt(mSaveBuyOil);
                        if (TextUtils.equals("1", mSaveSendWay)) {
                            //自提
                            if (mBuyOil < mRecordUserGet) {
                                SVProgressHUD.showInfoWithStatus(aty, "自提最少需要" + StringUtils.removePoint(mRecordUserGet + "") + "吨起");
                            } else {
                                return true;
                            }
                        } else {
                            //配送
                            if (mBuyOil < mRecordSend) {
                                SVProgressHUD.showInfoWithStatus(aty, "配送最少需要" + StringUtils.removePoint(mRecordSend + "") + "吨起");
                            } else {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 处理买油的量
     *
     * @param flag 0  减 1加
     */
    public void handOilNum(String msg, int flag) {
        int i = Integer.parseInt(msg);
        if (flag == 0) {
            if (StringUtils.isEmpty(mSaveSendWay)) {
                i--;
                if (i <= 0) {
                    mTxtDesc.setSelected(false);
                    mEditOil.setText("1");
                } else {
                    mTxtDesc.setSelected(true);
                    mEditOil.setText(i + "");
                }
            } else {
                if (TextUtils.equals("1", mSaveSendWay)) {
                    //自提
                    i--;
                    if (i <= mRecordUserGet) {
                        mTxtDesc.setSelected(false);
                        mEditOil.setText((int) mRecordUserGet + "");
                    } else {
                        mTxtDesc.setSelected(true);
                        mEditOil.setText(i + "");
                    }
                } else if (TextUtils.equals("2", mSaveSendWay)) {
                    //配送
                    i--;
                    if (i <= mRecordSend) {
                        mTxtDesc.setSelected(false);
                        mEditOil.setText((int) mRecordSend + "");
                    } else {
                        mTxtDesc.setSelected(true);
                        mEditOil.setText(i + "");
                    }
                }
            }
        } else {
            i++;
            mTxtDesc.setSelected(true);
            mEditOil.setText(i + "");
        }
        if (i <= 0) {
            calculateTotalMoney(1);
        } else {
            calculateTotalMoney(i);
        }
    }

    @OnClick({R.id.id_add_address_linear, R.id.id_choose_address_rela, R.id.id_order_desc_txt, R.id.id_order_add_txt, R.id.id_choose_send_way_rela, R.id.id_choose_invoice_rela, R.id.id_wish_send_time_rela, R.id.id_sure_pay_btn})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_add_address_linear:
                //添加地址
                showActivity(aty, FrequentlyAreasAty.class);
                break;
            case R.id.id_choose_address_rela:
                //选择地址
                showActivity(aty, FrequentlyAreasAty.class);
                break;
            case R.id.id_order_desc_txt:
                // 减
                handOilNum(mSaveBuyOil, 0);
                break;
            case R.id.id_order_add_txt:
                // 加
                handOilNum(mSaveBuyOil, 1);
                break;
            case R.id.id_choose_send_way_rela:
                // 配送方式
                ArrayList<String> mStr = new ArrayList<String>();
                for (CommonModel model : mSends) {
                    mStr.add(model.name);
                }
                chooseWheel(mStr, 1);
                break;
            case R.id.id_choose_invoice_rela:
                // 发票
                break;
            case R.id.id_wish_send_time_rela:
                // 期望送达时间
                mDateDialog.show();
                break;
            case R.id.id_sure_pay_btn:
                //  去支付
                if (checkData()) {
                    OilSendModel model = new OilSendModel();
                    model.supplyId = mOilDetailsModel.orgId;
                    model.deliveryMode = mSaveSendWay;
                    model.buyNumber = mSaveBuyOil + "000";
                    model.throughTime = mSaveWishTime;
                    model.name = mSaveGoodsName;
                    model.tel = mSaveGoodsTel;
                    model.location = mSaveGoodsAddress.replace("null", "");
                    model.amount = StringUtils.removePoint(mSaveTotalPrice);
                    model.mMayPay = mSavePay;
                    model.feeAmount = "0";
                    model.orderSrc = "2";
                    model.remark = mSaveRemark;
                    TransitAty.start4TransitAty(aty, IntentCode.General.JUMP_CARD_ORDER, model);
                }
                break;
        }
    }

    /**
     * 展示数据
     *
     * @param addressModel
     */
    public void showData(MyAddressModel addressModel) {
        if (null != addressModel) {
            mLinearNoAddress.setVisibility(View.GONE);
            mRelaHadAddress.setVisibility(View.VISIBLE);
            mSaveGoodsName = addressModel.getName();
            mTxtGoodsName.setText(mSaveGoodsName);
            mSaveGoodsTel = addressModel.getTel();
            mTxtGoodsTel.setText(mSaveGoodsTel);
            String address = addressModel.getLocation().replaceAll("|", "");
            mSaveGoodsAddress = addressModel.getLocation();
            mTxtGoodsAddress.setText(address);
        } else {
            mLinearNoAddress.setVisibility(View.VISIBLE);
            mRelaHadAddress.setVisibility(View.GONE);
        }
        List<OilDetailBannerModel> mBanners = mOilDetailsModel.bannerList;
        if (null != mBanners && !mBanners.isEmpty()) {
            ImageUtils.showRoundImg(aty, Protect.setPic(mBanners.get(0).smallPrefix), R.drawable.ic_bg_oil_sale, R.drawable.ic_bg_oil_sale, mImgoilPic);
        } else {
            mImgoilPic.setImageResource(R.drawable.ic_bg_oil_sale);
        }
        if (mOilDetailsModel.payType == 1) {
            //面议
//            mTxtOilPrice.setText("面议");
            mTxtOilPrice.setText("面议单价：" + Currency.returnDollar(mOilDetailsModel.tonPrice) + "/吨");
        } else if (mOilDetailsModel.payType == 2 || mOilDetailsModel.payType == 3) {
            //线上支付
            mTxtOilPrice.setText("单价：" + Currency.returnDollar(mOilDetailsModel.tonPrice) + "/吨");
        }
        String mOilTitle = "";
        if (mOilDetailsModel.oilType == 1) {
            mOilTitle = "柴油 0# " + (TextUtils.equals("1", mOilDetailsModel.oilModel) ? "普柴" : "国V");
        }
        mTxtOilTitle.setText(mOilTitle);
        mTxtOilDensity.setText("密度:" + mOilDetailsModel.oilDensity);
        mTxtOilType.setText(mOilDetailsModel.oilSourceName);

        mTxtDesc.setSelected(false);
        mTxtAdd.setSelected(true);
        mEditOil.setText("1");
        calculateTotalMoney(1);

        //配送方式
        int sendWay = mOilDetailsModel.deliveryMode;
        if (sendWay == -1) {
            CommonModel model = new CommonModel("1", "自提");
            CommonModel model1 = new CommonModel("2", "配送（不含运费）");
            mSends.add(model);
            mSends.add(model1);
        } else if (sendWay == 1) {
            CommonModel model = new CommonModel("1", "自提");
            mSends.add(model);
        } else if (sendWay == 2) {
            CommonModel model1 = new CommonModel("2", "配送（不含运费）");
            mSends.add(model1);
        }

    }

    /**
     * 计算总金额
     *
     * @param num 油的吨数
     */
    public void calculateTotalMoney(int num) {
        double total = num * Double.parseDouble(mOilDetailsModel.tonPrice);
        mTxtTotalPrice.setText("总计：" + Currency.returnDollar(total + "") + "（不含运费）");
        mSaveTotalPrice = total + "";
        mTxtPayPrice.setText("预付定金：" + Currency.returnDollar(total + "", mCalculateModel.calculatedValue + "") + "元");
        mSavePay = Currency.returnDollar(total + "", mCalculateModel.calculatedValue + "");
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != tag) {
            if (TextUtils.equals(tag, ConstantTag.GET_MY_DEFAULT_ADDRESS)) {
                //获取我的默认地址
                final MyAddressModel addressModel = (MyAddressModel) t;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (null != addressModel) {
                            showData(addressModel);
                        } else {
                            showData(null);
                        }
                    }
                });
            } else if (TextUtils.equals(tag, ConstantTag.GET_SINCE_MIN)) {
                //自提
                ConstantModel model = (ConstantModel) t;
                if (null != model) {
                    mRecordUserGet = Double.parseDouble(StringUtils.returnKG(model.key).replace("吨", ""));
                }
                mEditOil.setText((int) mRecordUserGet + "");
                calculateTotalMoney((int) mRecordUserGet);
            } else if (TextUtils.equals(tag, ConstantTag.GET_DISTRIBUTION_MIN)) {
                //配送
                ConstantModel model = (ConstantModel) t;
                if (null != model) {
                    mRecordSend = Double.parseDouble(StringUtils.returnKG(model.key).replace("吨", ""));
                    mEditOil.setText((int) mRecordSend + "");
                    calculateTotalMoney((int) mRecordSend);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        if (TextUtils.equals(event.type, ConstantTag.CHOOSE_MY_ADDRESS)) {
            //选择地址返回
            final MyAddressModel model = (MyAddressModel) event.model;
            if (null != model) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mLinearNoAddress.setVisibility(View.GONE);
                        mRelaHadAddress.setVisibility(View.VISIBLE);
                        mTxtGoodsName.setText(model.getName());
                        mSaveGoodsName = model.getName();
                        mTxtGoodsTel.setText(model.getTel());
                        mSaveGoodsTel = model.getTel();

                        String address = model.getLocation().replaceAll("|", "");
                        mSaveGoodsAddress = model.getLocation();
                        mTxtGoodsAddress.setText(address);
                    }
                });
            }
        } else if (TextUtils.equals(event.type, ConstantTag.NO_ADDRESS)) {
            //没有地址
            mLinearNoAddress.setVisibility(View.VISIBLE);
            mRelaHadAddress.setVisibility(View.GONE);
        } else if (TextUtils.equals(event.type, ConstantTag.OIL_SEND_CALLBACK_SUCCESS)) {
            //柴油批发回调成功
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
